// jQuery
// RequestJs.js
// JiraClient.js

class Mianban
{
    constructor()
    {
        this.Jira = new JiraClient(this.getConfig());
        this.addButton()
        this.user = {}
    }

    getConfig()
    {
        let options = {};
        try {
            let config = JSON.parse(localStorage.getItem('config'));
            options = config.target;
            if (options.url) {
                options.host = options.url;
            }
        } catch (e) {
            console.error('Something wrong with config', e);
            alert('Something wrong with config, see console have detail.');
        }

        return options;
    }

    getFilterConditions()
    {
        let conditions = JSON.parse(localStorage.getItem('config')).resources
            conditions = JSON.parse(conditions)
        let _conitions = []
        Object.keys(conditions).forEach((g) => {
            let tmp = conditions[g];
            Object.keys(tmp).forEach((n) => {
                _conitions.push(n.toLocaleLowerCase().replace(' ', '-'))
            });
        });
        console.log(_conitions)

        return _conitions
    }

    addButton()
    {
        let self = this;
        let selectHtml = '<option value="reset"> -- reset -- </option>';
        self.getFilterConditions().forEach((value, idx) => {
            selectHtml += '<option value="' + value + '">' + value + '</option>';
        })
        selectHtml = '<select class="developer-filter">' +  selectHtml + '</select><button id="user-filter">Filter</button>';
        let buttonHtml = '<li><button id="sync-sc-developer">fetch Developer</button></li><li>' + selectHtml + '</li>';

        jQuery('.aui-header-primary ul.aui-nav').append(buttonHtml);
        jQuery('#sync-sc-developer').on('click', (e) => {
            self.search()
        });

        jQuery('#user-filter').on('click', (e) => {
            if (jQuery('.developer-filter').val()=='reset') {
                jQuery('.ghx-issue').show();
            } else {
                jQuery('.ghx-issue').hide();
                jQuery('.' + jQuery('.developer-filter').val()).show();
            }
        })
    }

    createJQL()
    {
        let jql = 'issuetype in (Bug, Task) AND (CONDITIONS)';
        let conditions = new Array();
        jQuery('.js-issue .ghx-key a').each((idx, item) => {
            conditions.push('"summary" ~' + jQuery(item).attr('title'))
        })
       return jql.replace('CONDITIONS', conditions.join(' OR '))
    }

    async search()
    {
        let searchResult = new Array()
        let user = {}
        let regex = /^HPST-\d+/;
        let jql = this.createJQL()
        console.log('##JQL[' + jql + ']')
        let searchPromise = await this.Jira.search(jql, {size:200}).then(resp => resp.json()).then(function(result){
            if (result.total) {
                result.issues.forEach(function(issue) {
                    console.log('##issue:', issue)
                    var title = issue.fields.summary.match(regex);
                     searchResult.push({
                         key: (title==null) ? '' : title[0], //issue.fields.customfield_10700,
                         type: issue.fields.issuetype.name,
                         assignee: issue.fields.assignee?.displayName,
                         fixVersions: issue.fields.fixVersions,
                         status: issue.fields.status.name
                     })
                })
            }
        })

        jQuery('.issue-developer').remove()
        searchResult.forEach((issue,idx) => {
            let key = issue.assignee.toLocaleLowerCase().replace(' ', '-')
            user[key] = key
            jQuery('a.ghx-key-link[title="' + issue.key + '"]')
                .append('<br/><span class="issue-developer" style="color:blue;">' + issue.assignee + '</span> - <span style="color:red;"> ' + issue.status + '</span>')
                .parent().parent().parent().parent()
                .addClass(key);
        })

        console.log('##user', user)
    }
}
new Mianban();